<?php defined('SYSPATH') OR die('No direct access allowed.');

class DbDropDown_Plugin extends WB_FormItem {
	
	protected $list = array();
	protected $table, $field, $primary_key, $list_prefix, $list_suffix, $condition;
	protected $db_is_null =FALSE;
	
	public function __construct($name='', $params=array())
	{
		parent::__construct($name, $params);
		
		$this->table = isset($this->params['table']) ? $this->params['table'] : $this->db_table;
		$this->field = isset($this->params['field']) ? $this->params['field'] : $this->name;
		$this->primary_key = isset($this->params['primary_key']) ? $this->params['primary_key'] : 'id';
		$this->where = isset($this->params['where']) ? $this->params['where'] : '1';
		$this->list_prefix = isset($this->params['list_prefix']) ? $this->params['list_prefix'] : array();
		$this->list_suffix = isset($this->params['list_suffix']) ? $this->params['list_suffix'] : array();
		$this->db_is_null = in_array('db_is_null', $this->params);
		
		$this->table_columns[$this->name] = $this->table.'.'.$this->field;
		if ($this->table!=$this->db_table) $this->table_joins[] = array($this->table, $this->table.'.'.$this->primary_key.'='.$this->db_table.'.'.$this->name);
	}
	
	public function prep_db()
	{
		if ($this->db_is_null && empty($this->value)) return 'NULL';
		return parent::prep_db();
	}
	
	public function set_value($value, $type)
	{
		if (empty($value) && ! $this->db_is_null && in_array($type, array('add', 'edit')))
		{
			$this->error_msg = Kohana::lang('dbdropdown_plugin.err_must_chose', $this->get_label());
		}
		$this->value = $value;
	}

	
	/**
	 * Renders the form element
	 * 
	 * @return string
	 */
	public function render_item()
	{
		$str = $this->prefix;
		$str .= form::label($this->name, $this->label);
		$str .= form::dropdown($this->name, $this->get_list(), $this->value, html::attributes($this->attributes));
		$str .= $this->suffix;
		
		return $str;
	}
	
	private function get_list()
	{
		if (empty($this->list))
		{
			$db = Kohana::instance()->db;
			$query = $db->query('SELECT `'.$this->primary_key.'`, `'.$this->field.'` FROM `'.$this->table.'` WHERE '.$this->where);
			
			if ($this->db_is_null) $this->list[''] = Kohana::lang('dbdropdown_plugin.chose_one');
			foreach ($this->list_prefix as $key=>$val) $this->list[$key] = $val;
			foreach ($query->result_array(FALSE) as $row) $this->list[$row[$this->primary_key]] = $row[$this->field];
			foreach ($this->list_suffix as $key=>$val) $this->list[$key] = $val;
		}
		return $this->list;
	}
}

//End of DbDropDown_Plugin Library